// jscommon.js

// check browser version
var ns4 = (document.layers)? true:false;
var ns6 = (document.getElementById)? true:false;
var ie4 = (document.all)? true:false;
var ie5 = false;

if (ie4) {
	if (navigator.userAgent.indexOf('MSIE 5')>0) {
		ie5 = true;
	}
	if (ns6) {
		ns6 = false;
	}
}


// Capture events
if ( (ns4) || (ie4) || (ns6)) {
//	document.onmousemove = mouseMove;
	if (ns4) document.captureEvents(Event.MOUSEMOVE)
} else {
	// when events can't be captured
}

// it selects all the selectBox items or deselects them all
function selectAll(cell, selectBox, length)
{	
	if (cell.value == 0)
	{
		for (i = 0; i < length; i++)
			selectBox[i].checked = true;
		cell.value = 1;
	}
	else
	{
		for (i = 0; i < length; i++)
			selectBox[i].checked = false;
		cell.value = 0;
	}
}

// This is the master JavaScript file that is included with every
// HTML page that is shown using the Catalyst HTMLTemplate module.
// Changes should be tested thoroughly as they affect every page.

//// vars

function _set(key,value){
  this[key] = value;
}

function _get(key){
  return this[key];
}

function _delete(key){
  this[key] = null;
}

var doc;

if(document.all){
  doc = document.all;
}else{
  doc = document;
}

var help; // tracks the help window.  See functions below
var spellchecker; // tracks spell checker window.  See function for opening below.

//// browser detection

function BrowserObj(){
}

BrowserObj.prototype.set = _set;
BrowserObj.prototype.get = _get;
BrowserObj.prototype.remove = _delete;

var Browser = new BrowserObj();
Browser.set("isNetscape", false);
Browser.set("isIE", false);

var detect = navigator.userAgent.toLowerCase();
var browser_position, browser_match, browser_version;

// Check for exotic browser types first
if (checkIt('konqueror'))    { Browser.set("type", "Konqueror"); }
//else if (checkIt('omniweb')) { Browser.set("type", "OmniWeb"); }
//else if (checkIt('webtv'))   { Browser.set("type", "WebTV"); }
//else if (checkIt('icab'))    { Browser.set("type", "iCab"); }
else if (checkIt('safari'))  { Browser.set("type", "Safari"); }
else if (checkIt('opera'))   { Browser.set("type", "Opera"); }
else if (checkIt('msie'))    {
  Browser.set("isIE", true);
  Browser.set("type", "Internet Explorer");
}
else if (!checkIt('compatible')) {
  Browser.set("isNetscape", true);
  Browser.set("type", "Netscape Navigator");
  browser_version = detect.charAt(8);
}
else { Browser.set("type", "Unknown"); }

if (!browser_version) {
  browser_version = detect.charAt(browser_position + browser_match.length); 
}
Browser.set("version", browser_version);

if (checkIt('linux'))    { Browser.set("platform", "Linux"); }
else if (checkIt('x11')) { Browser.set("platform", "Unix"); }
else if (checkIt('mac')) { Browser.set("platform", "Mac"); }
else if (checkIt('win')) { Browser.set("platform", "Win"); }
else                     { Browser.set("platform", "Unknown"); }

function checkIt(string) {
  browser_position = detect.indexOf(string) + 1;
  browser_match = string;
  return browser_position;
}

// Get the document base href 
// Also provides a hack for tools that do not use <base>
function getDocumentBase() {
  var document_base;
  var catalyst_base = document.getElementById('catalyst_base');
  if (catalyst_base) {
    document_base = catalyst_base.href;
  } else {
    var loc = new String(document.location);
    document_base = loc.substr(0, loc.indexOf('secure'));
  }
  return document_base;
}

// Create an image object
function newImage(arg) {
  var rslt = new Image();
  rslt.src = arg;
  return rslt;
}

// Function to open the help window
function openHelp() {
  if (help != null && help.closed != true) {
    help.focus();
  } else {  
    help = window.open('#','helpwin','alwaysRaised=yes,width=700,height=500,resizable=yes,scrollbars=yes');
  }
}

// Function to close the help window.
function closeHelp() {
  if (help != null && help.closed != true) {
    help.close();
    help = null;
  }
}

// Function to open the spell checker window
function openSpellChecker() {
  if(spellchecker != null && spellchecker.closed != true){
    spellchecker.focus();
  }else{
    spellchecker = window.open("#", "spellWindow", "height=300,width=375,resizable=yes,status=yes,scrollbars=yes");
  }
}

// Function to set status bar message text.
function show(mess) {
  window.status = mess;
  return true;
}

///////////////////////  TEXT AREA EXPANSION CODE  /////////////////////

// Textarea object
function Textarea (textarea, mouse_x, mouse_y) {
  this.textarea = textarea;
  this.start_x = mouse_x;
  this.start_y = mouse_y;
  this.start_cols = parseInt(textarea.cols);
  this.start_rows = parseInt(textarea.rows);
}

// Resize function
function Textarea_resize (mouse_x, mouse_y) {
  var cols = this.start_cols + parseInt((mouse_x - this.start_x) / 8);
  var rows = this.start_rows + parseInt((mouse_y - this.start_y) / 15);
  if (cols >= 10) { // Min size is 10 cols
    this.textarea.cols = cols;
  }
  if (rows >= 5) {  // Min size of 5 rows
    this.textarea.rows = rows;
  }
}

// Make function a method of object.
Textarea.prototype.resize = Textarea_resize;

var selected_Textarea = null; // Variable to hold current textarea.

function startExpandTextarea(evt, textarea) {
  selected_Textarea = new Textarea(textarea, evt.screenX, evt.screenY);
  // set even handlers to deal with the events we're interested in now
  document.onmousemove = expandTextarea;
  document.onmouseup = stopExpandTextarea;
  return false;
}

// Called as the mouse is moved
function expandTextarea(evt) {
  if (document.all) {
    evt = window.event;
  }
  selected_Textarea.resize(evt.screenX, evt.screenY);
}

// Called once the user releases the mouse button (onMouseUp)
function stopExpandTextarea(evt) {
  selected_Textarea = null;
  // No longer interested in these events, so nuke them.
  document.onmousemove = null;
  document.onmouseup = null;
}

///////////////////////  INPUT FIELD EXPANSION CODE  /////////////////////

// Function that resizes text input fields on the fly.
// To function properly, you should put a size attribute on the
// input tag of the form element.  If you do not, this will 
// most likely not work in IE macintosh.

function sizeit (obj) {
  var MAXSIZE = 50;
  var dfs = parseInt(obj.size); // get current size

  if (isNaN(dfs) || dfs == 0) { // check if its defined.
    dfs = 20;                   // Netscape returns NaN, IE returns 0
  }                             // set it to 20 by default if a size was not defined
  // If the default size (or original size) is not known,
  // then set it here.  We need to save it so we know what
  // size to never go smaller than.

  var len = 0;      
  if (!obj.defaultsize) {
    obj.defaultsize = dfs;
    len = dfs;                  // default text may be bigger than size
  } else {                      // so set len to size first time only.
    len = obj.value.length;     // Get the length of the current value
  }

  // If the length is greater than the original size
  // and less than the max size, then set the size of 
  // the field to that value.
  if (len > obj.defaultsize && len < MAXSIZE) {
    obj.size = parseInt(len) + 2;
  }
}

//// Functions that highlight and unhighlight text

// Change the background-color of an object
var currently_highlighted;
var was_background_color;
function highlight(obj, bg_color) {
  if (Browser.get("isNetscape") && Browser.get("version") < 5.0) {
    return;
  } else {  
    var target = document.getElementById(obj);
    if (currently_highlighted) {
      currently_highlighted.style.backgroundColor = was_background_color;
    }
    was_background_color = target.style.backgroundColor;
    target.style.backgroundColor = bg_color; 
    currently_highlighted = target;
  }
}  

// Return background-color to previous value
function unhighlight() {
  if (currently_highlighted) {
    currently_highlighted.style.backgroundColor = was_background_color;
    currently_highlighted = "";
  }
}

// Change the font-weight of an object
var currently_bold;
var was_font_weight;
function makebold(obj) {
  if (Browser.get("isNetscape") && Browser.get("version") < 5.0) {
    return;
  } else {  
    if (currently_bold) {
      currently_bold.style.fontWeight = was_font_weight;
    }
    was_font_weight = obj.style.fontWeight;
    obj.style.fontWeight = "bold";
    currently_bold = obj;
  }
}  


// Return font-weight to previous value
function unbold() {
  if (currently_bold) {
    currently_bold.style.fontWeight = was_font_weight;
    currently_bold = "";
  }
}

function hideBlock(block) {
  document.getElementById(block).style.display = "none";
}

function showBlock(block) {
  document.getElementById(block).style.display = "block";
}  

//// pop-up calendar

var cal;
var keepgoing = false;
// variables that hold the objects to change
var monthmenu; 
var daymenu;
var yearmenu;
var adjust;

// This function sets the calendar's hidden values in "blank.html" so that
// that it will be able to set your pull down menus for month, day and year.
function register(){
  cal.caldata.monthmenu = monthmenu;
  cal.caldata.daymenu = daymenu;
  cal.caldata.yearmenu = yearmenu;
  cal.caldata.adjust = adjust;
}

// Wait function.  It waits for 1/2 second intervals continually
// checking to see if the blank.html page in the calendar frame
// has loaded.  The blank.html page changes the value of keepgoing
// to true and at that time this routine will run register.
function wait(){
  if(keepgoing == false){
    setTimeout("wait()",500);
  }else{
    register();
  }
}

// This function actually opens the calendar window.  Pass it the
// document objects for the month, day, and year select menus.
function openCalendar(months,days,years,a){
  monthmenu = months;
  daymenu = days;
  yearmenu = years;
  adjust = a;

  keepgoing = false; // in case they close window and open it again.
  if(cal != null && cal.closed != true){
    cal.focus();
  }else{
    cal = window.open("#", "calendarWindow", "width=220,height=220");
  }  
  
  if(keepgoing == false){
    setTimeout("wait()",500);
  }
}

//// form tools

// Function to append a slash to a string
function appendSlash(obj) {
  var val = obj.value;
  if (val.search(/\/\$/) == -1) {
    obj.value += "/";
  }
}


// These functions auto-check and uncheck groups of 1 or more
// checkboxes. Pass them a form field, ie 'doc.form.somecheck'
function checkAll(field) {
  if (field.length) {
    for (i = 0; i < field.length; i++) {
      field[i].checked = true;
    }
  } else {
    field.checked = true;
  }  
}

function uncheckAll(field) {
  if (field.length) {
    for (i = 0; i < field.length; i++) {
      field[i].checked = false;
    }
  } else {
    field.checked = false; 
  }  
}  

// This function is meant to be called from an onload event.  
// It finds the first non-hidden form element and brings it
// into focus.  If it is a text input form element, it will
// also select it.  You can pass an option form element to 
// override the auto-focus

var form_focus_disabled = false;
function formFocus(element) {
  if (form_focus_disabled) { form_focus_disabled = false; return false; }
  if (element) { 
    form_focus_disabled = true; 
    return _formFocusInput(element);
  }

  var first_form = document.forms[0];
  if (!first_form) { return false; }
  
  for (var i = 0; i < first_form.elements.length; i++) {
    if (_formFocusInput(first_form.elements[i])) { return true; }
  }
  return false;
}

function _formFocusInput(input) {
  if (input && input.type != "hidden") {
    input.focus();
    if (input.type == "text" || input.type == "textarea" || input.type == "password" || input.type == "file") {
      input.select();
    }
    return true;
  }
  return false;
}

function disableformFocus() {
  form_focus_disabled = true;
}

//// cookies

function Cookie(document, name, hours, path, domain, secure) {
  this.$doc    = document;
  this.$name   = name;
  this.$expire = (hours) ? new Date((new Date()).getTime() + hours*3600000) : null;
  this.$path   = (path) ? path : null;
  this.$domain = (domain) ? domain : null;
  this.$secure = (secure) ? true : false;
}

Cookie.prototype.store = function() {
  var cookieval = "";
  for (var prop in this) {
    if ((prop.charAt(0) == '$') || (typeof this[prop] == 'function')) continue;
    if (cookieval != "") cookieval += '&';
    cookieval += prop + ':' + escape(this[prop]);
  }  

  var cookie = this.$name + '=' + cookieval;
  if (this.$expire) cookie += '; expires=' + this.$expire.toGMTString();
  if (this.$path) cookie += '; path=' + this.$path;
  if (this.$domain) cookie += '; domain=' + this.$domain;
  if (this.$secure) cookie += '; secure';

  this.$doc.cookie = cookie;
}

Cookie.prototype.load = function() {
  var allcookies = this.$doc.cookie;
  if (allcookies == "") return false;

  var start = allcookies.indexOf(this.$name + '=');
  if (start == -1) return false; // cookie not defined for this page
  start += this.$name.length + 1;
  var end = allcookies.indexOf(';', start);
  if (end == -1) end = allcookies.length;
  var cookieval = allcookies.substring(start, end);

  var a = cookieval.split('&');
  for(var i = 0; i < a.length; i++) { a[i] = a[i].split(':'); }
  for(var i = 0; i < a.length; i++) { this[a[i][0]] = unescape(a[i][1]); }
  
  return true;
}  

Cookie.prototype.remove = function() {
  var cookie = this.$name + '=';
  if (this.$path) cookie += '; path=' + this.$path;
  if (this.$domain) cookie += '; domain=' + this.$domain;
  cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

  this.$doc.cookie = cookie;
}

//// window openers

var catgroupmemberswin;
function openGroupMembers(group) {
  if (catgroupmemberswin != null && catgroupmemberswin.closed != true) {
    catgroupmemberswin.focus();
  }
  var document_base = getDocumentBase();
  catgroupmemberswin = window.open(document_base+'secure/manage/group_members.cgi?group_id='+group,'groupmemberwin','height=500,width=500,resizable=yes,status=yes,scrollbars=yes');
}

var catgrouptoolswin;
function openLinkedTools(group) {
  if (catgrouptoolswin != null && catgrouptoolswin.closed != true) {
    catgrouptoolswin.focus();
  }
  var document_base = getDocumentBase();
  catgrouptoolswin = window.open(document_base+'secure/manage/group_tools.cgi?group_id='+group,'grouptoolswin','height=500,width=500,resizable=yes,status=yes,scrollbars=yes');
}
